package com.yjc.sunnyweather.util

import androidx.datastore.preferences.core.*
import androidx.datastore.preferences.rxjava2.RxPreferenceDataStoreBuilder
import com.yjc.sunnyweather.SunnyWeatherApplication
import io.reactivex.Single
import kotlinx.coroutines.ExperimentalCoroutinesApi

@OptIn(ExperimentalCoroutinesApi::class)
object DataStoreUtil {

    private val dataStore =
        RxPreferenceDataStoreBuilder(SunnyWeatherApplication.context,"config").build()

    fun putString(key: String, value: String){
        dataStore.updateDataAsync { preferences: Preferences ->
            val mutablePreferences = preferences.toMutablePreferences()
            mutablePreferences[stringPreferencesKey(key)] = value
            Single.just(
                mutablePreferences
            )
        }
    }

    fun getString(key: String, defaultValue: String): String{
        val value = dataStore.data().blockingFirst()[stringPreferencesKey(key)]
        return value ?: defaultValue
    }

    private fun putInt(key: String, value: Int) {
        dataStore.updateDataAsync { preferences: Preferences ->
            val mutablePreferences = preferences.toMutablePreferences()
            mutablePreferences[intPreferencesKey(key)] = value
            Single.just(mutablePreferences)
        }
    }

    private fun getInt(key: String, defValue: Int): Int {
        val value = dataStore.data().blockingFirst()[intPreferencesKey(key)]
        return value ?: defValue
    }

    private fun putBoolean(key: String, value: Boolean) {
        dataStore.updateDataAsync { preferences: Preferences ->
            val mutablePreferences = preferences.toMutablePreferences()
            mutablePreferences[booleanPreferencesKey(key)] = value
            Single.just(mutablePreferences)
        }
    }

    private fun getBoolean(key: String, defaultValue: Boolean): Boolean {
        val value = dataStore.data().blockingFirst()[booleanPreferencesKey(key)]
        return value ?: defaultValue
    }

    private fun putDouble(key: String, value: Double) {
        dataStore.updateDataAsync { preferences: Preferences ->
            val mutablePreferences = preferences.toMutablePreferences()
            mutablePreferences[doublePreferencesKey(key)] = value
            Single.just(mutablePreferences)
        }
    }

    private fun getDouble(key: String, defValue: Double): Double {
        val value = dataStore.data().blockingFirst()[doublePreferencesKey(key)]
        return value ?: defValue
    }

}